<template>
	<view class="">
		<headerSpaceBetweenVue>
			<template #icon>
				<text @click="addArt()">发布</text>
			</template>
			<template #title>发布文章</template>
		</headerSpaceBetweenVue>
		<view class="detailBanner">
			<view class="form">
				<input type="text" v-model="formData.title" placeholder="标题(50字)" class="title" maxlength="50" />
				<!-- 富文本编辑器 -->
				<view class="textBox">
					<sp-editor editorId="editor" :toolbar-config="toolbarConfig" @input="inputOver" placeholder="请输入内容"
						@upinImage="upinImage" @init="initEditor" @overMax="overMax" @addLink="addLink"></sp-editor>
				</view>
				<uni-section title="选择分类" type="line">
					<uni-data-select v-model="formData.cate_id" :localdata="cateList"
						@change="changeCate"></uni-data-select>
				</uni-section>
				<uni-section title="文章类型" type="line">
					<radio-group @change="changeType">
						<label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in artType"
							:key="item.value">
							<radio :value="item.value" :checked="index === checkType" />
							{{item.name}}
						</label>
					</radio-group>
				</uni-section>
				<uni-section title="隐藏内容" type="line" v-if="formData.type !=1">
					<textarea rows="6" v-model="formData.hide_content" class="content" maxlength="1000"
						placeholder="请输入隐藏内容"></textarea>
				</uni-section>
				<uni-section title="积分数量" type="line" v-if="formData.type == 2">
					<input type="number" value="1" v-model="formData.score" placeholder="请输入积分数量" class="score"
						maxlength="50" /></uni-section>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		baseUrl
	} from '@/utils/request';
	import {
		apiAddArticle,
		apiArtUploadImg,
		apiGetCategory,
		apiReadArt
	} from '@/api/apis';
	import headerSpaceBetweenVue from '@/components/header-space-between/header-space-between.vue';
	export default {
		data() {
			return {
				editorIns: null,
				toolbarConfig: {
					excludeKeys: ['direction', 'video', 'export', 'lineHeight', 'letterSpacing', 'listCheck'],
					iconSize: '20px',
					iconColumns: 10
				},
				content: '',
				formData: {
					title: '',
					content: '',
					// 隐藏内容
					hide_content: '',
					// 文章积分
					score: 1,
					cate_id: null,
					type: 1
				},
				cateList: [],
				artType: [{
					value: '1',
					name: '直接查看',
					checked: 'true'
				}, {
					value: '3',
					name: '回复查看',
				}, {
					value: '2',
					name: '积分查看',
				}],
				checkType: 0

			};
		},
		onLoad(e) {
			this.cate_id = e.cate_id
			this.loadCateList()
		},
		components: {
			headerSpaceBetweenVue,
		},
		methods: {
			/**
			 * 获取输入内容
			 * @param {Object} e {html,text} 内容的html文本，和text文本
			 */
			inputOver(e) {
				console.log('==== inputOver :', e)
				this.formData.content = e.html
			},
			/**
			 * 超出最大内容限制
			 * @param {Object} e {html,text} 内容的html文本，和text文本
			 */
			overMax(e) {
				console.log('==== overMax :', e)
			},
			/**
			 * 编辑器就绪
			 * @param {Object} editor 编辑器实例，你可以自定义调用editor实例的方法
			 * @tutorial editor组件 https://uniapp.dcloud.net.cn/component/editor.html#editor-%E7%BB%84%E4%BB%B6
			 * @tutorial 相关api https://uniapp.dcloud.net.cn/api/media/editor-context.html
			 */
			initEditor(editor) {
				this.editorIns = editor // 保存编辑器实例
				// this.preRender()
			},
			preRender() {
				// 初始化编辑器内容
				this.editorIns.setContents({
					html: this.content
				})
			},
			/**
			 * 直接运行示例工程插入图片无法正常显示的看这里
			 * 因为插件默认采用云端存储图片的方式
			 * 以$emit('upinImage', tempFiles, this.editorCtx)的方式回调
			 * @param {Object} tempFiles
			 * @param {Object} editorCtx
			 */
			async upinImage(tempFiles, editorCtx) {
				/**
				 * 本地临时插入图片预览
				 * 注意：这里仅是示例本地图片预览，因为需要将图片先上传到云端，再将图片插入到编辑器中
				 * 正式开发时，还请将此处注释，并解开下面 使用 uniCloud.uploadFile 上传图片的示例方法 的注释
				 * @tutorial https://uniapp.dcloud.net.cn/api/media/editor-context.html#editorcontext-insertimage
				 */
				// #ifdef MP-WEIXIN
				// 注意微信小程序的图片路径是在tempFilePath字段中
				editorCtx.insertImage({
					src: tempFiles[0].tempFilePath,
					width: '80%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
					success: function() {}
				})
				// #endif
				// #ifndef MP-WEIXIN
				let tmpFile = tempFiles[0].path
				await apiArtUploadImg({
					url: tmpFile
				}).then((res) => {
					const data = JSON.parse(res)
					if (data.code == 200) {
						editorCtx.insertImage({
							src: baseUrl + data.data.src,
							width: '80%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
							success: function(res) {}
						})
					} else {
						uni.showToast({
							title: data.msg,
							icon: "none"
						})
					}
				})
				// #endif
			},

			/**
			 * 添加超链接
			 * @param {Object} e { text: '链接描述', href: '链接地址' }
			 */
			addLink(e) {
				console.log('==== addLink :', e)
			},
			tip(content) {
				uni.showToast({
					title: content,
					icon: "none"
				})
			},
			// 发布文章
			async addArt() {
				if (this.formData.title == "" || this.formData.content == "") {
					this.tip("请将内容输入完整")
					return
				}
				if (this.formData.type == 2 && this.formData.score <= 0) {
					this.tip("积分需大于0")
					return
				}
				if (this.formData.cate_id == null) {
					this.tip("请选择文章分类")
					return
				}
				if (this.formData.type != 1 && this.formData.hide_content == "") {
					this.tip("隐藏内容不能为空")
					return
				}
				await apiAddArticle(this.formData).then(res => {
					if (res.code == 200) {
						uni.showToast({
							title: "发布成功,请耐心等待审核"
						})
						uni.switchTab({
							url: "/pages/mine/mine"
						})
					} else {
						uni.showToast({
							title: res.msg,
							icon: "none",
							position: "bottom"
						})
					}

				})
			},
			// 改变文章分类
			changeCate(e) {
				this.formData.cate_id = e
			}, // 改变文章类型
			changeType: function(evt) {
				for (let i = 0; i < this.artType.length; i++) {
					if (this.artType[i].value === evt.detail.value) {
						this.checkType = i;
						this.formData.type = this.artType[i]['value']
						break;
					}
				}
			},

			async loadCateList() {
				await apiGetCategory({
					pid: this.cate_id
				}).then(res => {
					if (res.data.length == 0) {
						uni.showToast({
							title: '该分区暂无分类',
							icon: 'none'
						})
						uni.navigateBack()
						return
					}
					this.cateList = res.data.map((item, index) => {
						item['value'] = item.id
						item['text'] = item.cate_name
						return item
					})
				})
			}
		},
	};
</script>

<style lang="scss" scoped>
	.detailBanner {
		position: relative;
		padding: 20rpx;
		padding-top: calc(var(--status-bar-height) + 100rpx);

		.textBox {
			height: 460px;

			.editor {
				height: 460px;
			}

			.datalist {
				display: flex;
				justify-content: space-between;
			}
		}


		.form {

			.title,
			.score {
				height: 80rpx;
			}

			.title,
			.content,
			.hide-content,
			.score {
				width: 100%;
				border: 2rpx solid #e5e5e5;
				padding: 10rpx;
				border-radius: 10rpx;
				margin: 10rpx 0;
			}
		}
	}
</style>